import { ItemDat } from '../../Tools/QType';
import ShopItem from './ShopItem';
import Db from '../../Tools/Db';
import TipPanel from '../MenuManager/TipPanel';
import QGame from '../../Tools/QGame';
const {ccclass, property} = cc._decorator;

@ccclass
export default class ShopPanel extends cc.Component {
    private img:cc.Sprite;
    /** 当前展示的商品 */
    private currentItemDat:ItemDat;
    /** 购物车 */    
    private car:{item:ItemDat,count:number}[] = [];

    @property(cc.Prefab)
    public shopItemPrefab:cc.Prefab=null

    /**
     * 商品父级
     */
    private goodsParent:cc.Node;
    /**
     * 玩家持有金钱
     */
    private money:cc.Label;
    /** 消费金钱 */
    private useMoney:cc.Label;
    /** 关闭窗口按钮 */
    private close:cc.Node;
    private TipPanel:TipPanel;
    /** 购买按钮 */
    private buyBtn:cc.Node;
    /** 标题 */
    private title:cc.Label;
    onLoad(){
        this.img = this.node.getChildByName("Img").getChildByName("sprite").getComponent(cc.Sprite);
        this.goodsParent = cc.find("view/content",this.node);
        this.money = cc.find("total/money/value",this.node).getComponent(cc.Label);
        this.useMoney = cc.find("total/use/value",this.node).getComponent(cc.Label);
        this.title = this.node.getChildByName("title").getComponent(cc.Label);
        this.buyBtn = cc.find("total/buy",this.node);
        this.buyBtn.on(cc.Node.EventType.TOUCH_END,this.Buy,this);
        this.close = this.node.getChildByName("close");
        this.close.on(cc.Node.EventType.TOUCH_END,()=>{
            this.node.active = false;
        })
        this.TipPanel = this.node.getChildByName("TipPanel").getComponent(TipPanel);
        this.img.node.on(cc.Node.EventType.TOUCH_END,this.showTip,this);                
        this.node.on("CommodityShow",this.CommodityShow,this);  
    }


    start(){        
    }

    /** 商品展示 */
    CommodityShow(event:cc.Event.EventCustom){
        let obj = event.getUserData() ;
        let dat = obj.item as ItemDat;
        let count = obj.count;
        
        //数量变更时 更新购物车数据
        let index = this.car.findIndex(item=>{
            return item.item.id==dat.id
        }) 

        if(index>-1){
            //已存在购物车中
            this.car[index] = obj
        }else{
            this.car.push(obj)
        }
        this.updateUI();


        
        if(this.currentItemDat!=dat){
            this.currentItemDat = dat;
            this.img.spriteFrame = cc.loader.getRes("Item/"+dat.code,cc.SpriteFrame);    
        }
    }

    /** 打开商店 */
    openShop(items:number[]){
        this.node.active = true;
        this.img.spriteFrame = null;
        
        //初始化商店商品
        this.goodsParent.removeAllChildren();
        for(let i=0;i<items.length;i++){
            let node = cc.instantiate(this.shopItemPrefab);
            node.parent = this.goodsParent;
            let shopItem = node.getComponent(ShopItem);
            shopItem.setDat(Db.Instance.getItem<ItemDat>("Item",items[i]))            
        }
        this.fulfill(true);
    }

    /** 更新
     * 消费金钱
     */
    updateUI(){
        this.hideTip();
        //计算购物车中，商品总值
        let s = this.car.map(item=>{
            return item.item.price*item.count
        })
        this.useMoney.string =  s.reduce((total,num)=>{
            return total+num;
        }).toString()
    }

    /** 显示商品详细信息 */
    showTip(){    
        if(!this.currentItemDat)return;        
        this.TipPanel.itemDat = this.currentItemDat;
    }
    /** 隐藏商品详细信息 */
    hideTip(){        
        this.TipPanel.itemDat = null;
    }

    /**
     * 购买物品
     */
    Buy(){
        //获取商品总值
        let sum =  parseInt(this.useMoney.string);
        //获取当前用户持有金钱
        let money = QGame.Instance.money;
        if(money<sum){
            this.title.string = "金额不足";
        }else{
            this.title.string = "购买成功";
            //将购物车中的物品加入到背包中
            this.car.forEach(item=>{
                QGame.Instance.Backpack.add(item.item.id,item.count)
            })          
            QGame.Instance.changeMoney(-1*sum);
            this.fulfill();
        }
    }

    /**
     *  完成购物 
     *  重置一些数据
     * flag=true 第一次执行
    */
    fulfill(falg:boolean=false){
        this.money.string = QGame.Instance.money.toString();
        this.useMoney.string = "0";     
        this.title.string = " ";
        //初始化购物车
        this.car = [];
        if(!falg){
            this.node.getComponentsInChildren(ShopItem).forEach(item=>{
                item.reset();
            })    
        }
    }
}
